<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('头程计划单-新增and修改')" />
	<th:block th:include="include :: businessCSS" />
	<style>
        .main-content{position: relative;}
        .topbtns{position:fixed;top: 0;width: 100%;z-index: 9999;background-color: #fff;}
		.preservationBtn{padding: 10px;margin: 0;position: fixed;top: 0;z-index: 9999;background: #fff;width: 100%;}
		.preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 5px;cursor: pointer;}
		/* .layui-border-box{height: 350px !important;}
		.layui-table-body{height: 240px !important;} */
		.layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}
        .layui-table-tool-self{display: none;}

	</style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
		<div class="north">
			<th:block th:include="include :: business_btn" />
			<th:block th:include="include :: business_tp2('top')" />
		</div>
		<div class="mid-content">
            <table class="layui-hide" id="dhtable" lay-filter="dhtable"></table>
            <!-- <script type="text/html" id="barDh">
                <button class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" th:disabled="${enableEdit} == 1 ?false:true" lay-event="del">&nbsp;删除</button>
            </script> -->
            <script type="text/html" id="zjtoolbar">
                <div style="padding: 16px;display: flex;justify-content: space-between;">
                    <div  style="font-weight: 700;font-size: 18px;">商品列表</div>
            		<div>
                        <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="addbtn" id="btn-sh">新增</button>
                        <button class="layui-btn layui-btn-danger dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">删除</button>
            		</div>
            	</div>
            </script>
        </div>
        <th:block th:include="include :: pageFooter" /> 
    </form>
	</div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: inlineJS" />
<script th:src="@{/dhecp/js/dh-toFixed.js}"></script>


<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix = ctx + "business/productbasis",
    	prefix2 = ctx + "base/company";

	var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
	var fieldsHiddenList = [[${fieldsHiddenList}]];

	var moduleTable = [[${moduleTable}]];
	var enableEdit = [[${enableEdit}]];
    //商品表格基础信息
	var gridColumns = [[${gridColumns}]];
    // 商品列表数据
    var List=[[${List}]];
    //子件列表数据
    var sonList=[[${sonList}]];
    //材质列表
	var textureList = [[${textureList}]];
	//材质最大值
	var texture = $('#priceQualityExtra').val();
	//材质名称
	var surchargeMaterialMax = $('#surchargeMaterialMax').val();
	//品名数量
	var gradeNum = new Set();
	//梯度
	var logisticsMmodeGrads = [[${logisticsMmodeGrads}]];
	//抛重梯度
	var logisticsMmodeInfoItems = [[${logisticsMmodeInfoItems}]];
	//品名梯度
	var wlpmtdList = [[${wlpmtdList}]];

	var listData1=List ?List:[]
	var gaugeMaintenanceList=[[${gaugeMaintenanceList}]]?[[${gaugeMaintenanceList}]]:[]
	var listData2=sonList ?sonList:[]
	var $,layer,form,table,nid,noTable;
	//A1
	var a1 = 0;
	//最终箱数
	var issNum = 0;

	layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$,layer = layui.layer,form = layui.form,laydate = layui.laydate,util = layui.util,element=layui.element,upload = layui.upload,table = layui.table;
        beforeInit();//表单初始化之前的动作集合
		//初始化操作
		headcom3()
        nid=$('#nid').val();
         // 保存按钮事件变化
        $(function(){
           $('.tp-save').attr('onclick','')
           $('.tp-save').attr('lay-filter','btn-edit')
           $('.tp-save').attr('lay-submit',true)
        })

        
        // 保存操作
        form.on('submit(btn-edit)', function(data){
            var is_return = false//是否中断保存
            fieldsList.map((v,i)=>{
                if(v.fieldFrontRequired){
                    if(!$('#'+v.fields).val()){
                         layer.msg(v.fieldName+'不能为空')
                         is_return=true
                    }
                }
            })
			if(is_return) return;

			//商品列表不能为空
			if(listData1.length == 0){
				layer.msg('商品列表不能为空');
				return;
			}
			if (Number($('#numProName').val())> Number($('#numMaxProName').val())){
				layer.msg('已超出物流的上限品名数,请核实后在操作!');
				return
			}
			//详情
			for(var i = 1; i < gridColumns.dictionaryForPageFieldList.length; i++){
				if(gridColumns.dictionaryForPageFieldList[i].fieldFrontRequired){
					//判断是否为空
					if (listData1.some(items => items[gridColumns.dictionaryForPageFieldList[i].fields] == null || items[gridColumns.dictionaryForPageFieldList[i].fields] == ""
							|| items[gridColumns.dictionaryForPageFieldList[i].fields] == undefined)){
						if (gridColumns.dictionaryForPageFieldList[i].fields == 'numPlanDeliver'){
							layer.msg(gridColumns.dictionaryForPageFieldList[i].fieldName+'不能为0');
						} else {
							layer.msg(gridColumns.dictionaryForPageFieldList[i].fieldName+'不能为空');
						}
						is_return=true;
						break;
					}
				}
			}
			if(is_return) return;
			//禁用材质
			var forbiddenTexture = [];
            listData1.map((v,i)=>{
                v.iid=i+1
				if ($('#creationMethod').val() == '自动'){
					if(v.fnsku.indexOf("B") == 0) {
						is_return=true;
						layer.msg('自动创建头程,FNSKU必须为亚马逊条形码!');
						return;
					}
				}
				//判断是否是混合材质
				if (v.nameMaterialCn != null && typeof v.nameMaterialCn != "undefined") {
					if (v.nameMaterialCn.indexOf(",") == -1) {
						//赋值材质附加费(取最大值)
						for (let j = 0; j < textureList.length; j++) {
							if (textureList[j].materialName == v.nameMaterialCn) {
								if (textureList[j].isForbidden == '是'){
									forbiddenTexture.push(textureList[j].materialName)
								}
							}
						}
					} else {
						var nameMaterialCnList = v.nameMaterialCn.split(",");
						nameMaterialCnList.forEach(item => {
							for (let j = 0; j < textureList.length; j++) {
								if (textureList[j].materialName == item) {
									if (textureList[j].isForbidden == '是'){
										forbiddenTexture.push(textureList[j].materialName)
									}
								}
							}
						});
					}
				}
            })
			if(forbiddenTexture.length != 0) {
				is_return=true;
				layer.msg($('#nameLogsticsWay').val() + '不允许发以下材质:'+forbiddenTexture.join() + ',请核实后再操作!');
				return;
			}
			if(is_return) return;
			listData2.map((v,i)=>{
                v.iid=i+1
            })
			updateNew(listData1,gradeNum,textureList,logisticsMmodeGrads,logisticsMmodeInfoItems,0);
			//货件方式选择自动增加一个判断
			if ($('#creationMethod').val() == '自动'){
				$.modal.confirmCom('货件创建方式选择自动,是否继续保存？', function (result) {
					if (result == true){
						isSinglePassCrane(data);
					}
				})
			} else {
				isSinglePassCrane(data);
			}


        });





        // 初始化表格
            $.tablelist.init({
                elem: '#dhtable'
                ,data: listData1
                , page: false
                , even: true
                , limit: 10000
                , totalRow: gridColumns.totalRow
                , cols: [gridColumns.gridBody]
                , toolbar: '#zjtoolbar'
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , height: '320'
                , done: function (res, curr, count) {
                    listData1 = table.cache.dhtable;//每次重载都赋值更新表缓存
					fixTotal(this);//修复合计行固定列问题
					rowheight(res, curr);//修复合计行固定列问题
					detailUpload();
                },success:function(a,b,c){
                        console.log(a,b,c)
                }
            });


        //监听单元格编辑
        table.on('edit(dhtable)', function(obj){
			var weightRealPredict = 0;
			var weightVolPredict = 0;
			var toPurchasePrice = 0;
			//箱规单箱数量
			var dxNum = 0;
			var isjx=true;
			var isxu=true;
			var isDe=true;
			var msgDe = '';
			var gaugeList = [];
			listData1.map((n,m)=>{
				if(obj.data.guidKc == n.guidKc){
					var regular = /^([1-9]{1}[0-9]{0,7})$/  //正数 （不包括小数）
					if (!regular.test(n.numPlanDeliver)) {
						n.numPlanDeliver = 0;
						isjx = false;
						return
					}
					if (Number(n.numPlanDeliver) > Number(n.numStock)) {
						n.numPlanDeliver = 0;
						isxu = false;
						return
					}
					//海外仓 计划发货数量必须为箱规数量的倍数，如填写不正确，审核需提示为几的倍数。如果同一个商品存在多个箱规时，需弹出选择箱规标准。
					if ($('#isDeliver').val() == 1){
						for (var i = 0; i <gaugeMaintenanceList.length; i++) {
							//仓库相同  编号相同
							if (n.commodityCode == gaugeMaintenanceList[i].code &&  gaugeMaintenanceList[i].warehouseAddress == $('#warehouseAddress').val()){
								gaugeList.push(gaugeMaintenanceList[i])
							}
						}
						if (gaugeList.length == 0){
							n.numPlanDeliver = 0;
							n.gaugeMaintenanceId = null;
							n.gaugeMaintenanceNum = 0;
							isDe = false;
							msgDe = '该商品未箱规维护,请维护后重新打开制单页面!'
							return
						}
						if (gaugeList.length >= 1){
							var str = `<div class="tablebody"><table class="layui-table zjtable">
										<thead><tr>
										<th class="layui-input-block">
											<input type="checkbox" id="all" name="allIndex" lay-skin="primary" title="全选" onclick="checkAll()">
										</th>
										<th>商品编码</th><th>商品名称</th>
										<th>仓库名称</th><th>单箱数量</th>
										<th>箱子长度(cm)</th><th>箱子宽度(cm)</th>
										<th>箱子高度(cm)</th><th>箱子重量(kg)</th>
										</tr>
										</thead><tbody id="tbody">`;
							$.each(gaugeList, function (i, v) {
								str += `<tr>`;
								str += `<td><input type="checkbox" class="chBox"  lay-skin="primary"  onclick="checkOne()"></td>`;
								str += `<td>${v.code}</td>`;
								str += `<td>${v.name}</td>`;
								str += `<td>${v.warehouseAddress}</td>`;
								str += `<td>${v.num}</td>`;
								str += `<td>${v.length}</td>`;
								str += `<td>${v.width}</td>`;
								str += `<td>${v.height}</td>`;
								str += `<td>${v.weight}</td>`;
								str += `</tr>`;
							});
							str += `</tbody></table></div>`;
							layer.open({
								type: 1,
								area: [($(window).width() - 200) + 'px', ($(window).height() - 100) + 'px'],
								fix: false,//不固定
								offset: '10%',//距离顶部
								maxmin: true,//最大最小化
								shade: 0.3,//遮罩
								title: '箱子维护',
								content: str,
								btn: ['确定'],
								shadeClose: false,// 弹层外区域关闭
								yes: function (index, layero) {
									let objChBox = document.getElementsByClassName("chBox");
									var gaugeListNew = [];
									for (let i = 0; i < objChBox.length; i++) {
										if (objChBox[i].checked) {
											gaugeListNew.push(gaugeList[i]);
										}
									}
									if(gaugeListNew.length == 0){
										layer.msg('请选择一条数据,请核实后再操作!')
										return
									}else if(gaugeListNew.length > 1){
										layer.msg('只允许选择一条数据,请核实后再操作!')
										return
									}else {
										listData1.map((t,j)=> {
											if (t.guidKc == obj.data.guidKc) {
												t.gaugeMaintenanceId = gaugeListNew[0].id
												t.gaugeMaintenanceNum = gaugeListNew[0].num
												//判断倍数
												if (Number(t.numPlanDeliver)%Number(gaugeListNew[0].num) !== 0){
													t.numPlanDeliver = 0;
													t.gaugeMaintenanceId = null;
													t.gaugeMaintenanceNum = 0;
													layer.msg('计划发货数量必须为'+gaugeListNew[0].num+'的倍数')
												}else {
													//手动不允许超过10箱
													if($('#creationMethod').val() == '手动'){
														issNum = 0;
														listData1.map((t,j)=> {
															issNum = issNum + (Number(t.numPlanDeliver)/Number(t.gaugeMaintenanceNum))
														})
														if (issNum > 10){
															t.numPlanDeliver = 0;
															t.gaugeMaintenanceId = null;
															t.gaugeMaintenanceNum = 0;
															layer.msg('手动情况下不允许超过10箱!')
															return
														}
													}
												}
											}
										})
										updateNew(listData1,gradeNum,textureList,logisticsMmodeGrads,logisticsMmodeInfoItems,1);
										layer.close(index);
									}
								},
								cancel: function(index, layero){
									listData1.map((t,j)=> {
										if (t.guidKc == obj.data.guidKc) {
											t.numPlanDeliver = 0;
											t.gaugeMaintenanceId = null
										}
									})
									updateNew(listData1,gradeNum,textureList,logisticsMmodeGrads,logisticsMmodeInfoItems,1);
								},
							})
						}
					}
				}
			})

			updateNew(listData1,gradeNum,textureList,logisticsMmodeGrads,logisticsMmodeInfoItems,1);

			if(!isjx)return layer.msg('计划发货数量只允许输入正整数,请核实后在操作!')
			if(!isxu)return layer.msg('计划发货数量不允许超过库存数量,请核实后在操作!')
			if(!isDe)return layer.msg(msgDe)
		});






        //商品表格操作
        table.on('toolbar(dhtable)', function (obj) {
            var selectedObject=""
            sessionStorage.setItem('dhtable',JSON.stringify(table.cache.dhtable))
            table.cache.dhtable.map((v,i)=>{
                if(selectedObject){
                    selectedObject+=','+v.guidKc
                }else{
                    selectedObject+=v.guidKc
                }
            })
            switch (obj.event) {
                case 'addbtn':
					if ($('#nameLogsticsWay').val() == ''){
						layer.msg('物流方式未填写,请填写后在操作!');
						return
					}
					if (Number($('#numProName').val())>= Number($('#numMaxProName').val())){
						layer.msg('已超出物流的上限品名数,请核实后在操作!');
						return
					}
					if ($('#codeCompany').val() == ''){
						layer.msg('公司名称未填写,请填写后在操作!');
						return
					}
			    layer.open({
                	type: 2,
                	area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
                	fix: false,//不固定
                	offset: '10%',//距离顶部
                	maxmin: true,//最大最小化
                	shade: 0.3,//遮罩
                	title: '商品列表',
					content: "/business/fbaplanorder/select2?pagetype=checkbox&by=direct&fmoduleTable="+moduleTable+"&selectedObject="+selectedObject+"&vGsBm="+$('#codeCompany').val()+"&warehouseAddress="+$('#warehouseAddress').val(),
					btn: ['确定', '取消'],
                	shadeClose: true,// 弹层外区域关闭
                	yes: function(index, layero){
						var res = window["layui-layer-iframe" + index].callbackdata();
						if(res.length > 0){
							gradeNum.clear();
							// console.log("res", res);
							$.each(res,function(i,v){
                                v.commodityCode=v.code
								v.name=v.name
								v.sku= "";
                                v.nameGoodsCn= v.nameCn;
                                v.nameGoodsEn= v.nameEn;
                                v.codeGoodsHs= v.codeHs;
                                v.nameMaterialCn= v.materialCn;
                                v.nameMaterialEn= v.materialEn;
                                v.priceIn= v.priceIn;
                                v.codeStockLocation= v.vHw;
                                v.codeStockArea= v.vKq;
                                v.codeStockOn= v.gDepot;
                                v.spGuid= v.spId;
                                v.numStock= v.productNum;
                                v.numPlanDeliver= 0;
                                v.surplusStock= v.numStock - v.numPlanDeliver;
								v.weightPackage= toFixed((v.productWeight/1000),2);
								v.lengthPackage= v.productLength;
								v.widthPackage= v.productWidth;
								v.heightPackage= v.productHeight;
                                v.weightPredict= 0;
                                v.weightVolPredict= 0;
                                v.vDFilesDefault= '无附件';
                                v.vSfJp= v.vSfJp;
								console.log("v", v);
								//判断是否是混合材质
								if (v.nameMaterialCn != null && typeof v.nameMaterialCn != "undefined") {
									if (v.nameMaterialCn.indexOf(",") == -1) {
										//赋值材质附加费(取最大值)
										for (let j = 0; j < textureList.length; j++) {
											if (textureList[j].materialName == v.nameMaterialCn) {
												if (textureList[j].materialCost > texture) {
													texture = textureList[j].materialCost
													surchargeMaterialMax = textureList[j].materialName;
												}
											}
										}
									} else {
										var nameMaterialCnList = v.nameMaterialCn.split(",");
										nameMaterialCnList.forEach(item => {
											for (let j = 0; j < textureList.length; j++) {
												if (textureList[j].materialName == item) {
													if (textureList[j].materialCost > texture) {
														texture = textureList[j].materialCost
														surchargeMaterialMax = textureList[j].materialName;
													}
												}
											}
										});
									}
								}
								//设置表头附加费材质
								$('#priceQualityExtra').val(texture);
								//设置最大附加费材质
								$('#surchargeMaterialMax').val(surchargeMaterialMax);
								//设置预估材质附加费=材质计费*重量
								$('#priceQualityExtraPredict').val(texture*$('#weightCalPredict').val());
								//不一样的品名数=(商品中文、海关编码、材质中文只要一个不同)
								var join = v.nameGoodsCn + '-' + v.codeGoodsHs + '-' +v.nameMaterialCn;
								gradeNum.add(join);
								$('#numProName').val(gradeNum.size);
								//判断是否是拼票
								if ($('#stateShareTicketName').val() == '是'){
									//1.预估计重<单票起重的二分之一,实际品名数=免费品名数/2&向下取整
									let numWeightCal =$('#weightCalPredict').val()<$('#singlePassCrane').val()/2;
									//实际品名数
									let numProName = gradeNum.size;
									let numFreeProName;
									if (numWeightCal){
										numFreeProName = $('#numFreeProNameNew').val()== 0?0: Math.floor($('#numFreeProNameNew').val()/2)
									}
									//2.预估计重>=单票起重的二分之一,实际品名数=免费品名数/2&向上取整
                                    if (!numWeightCal && $('#weightCalPredict').val()<$('#singlePassCrane').val()){
										numFreeProName = $('#numFreeProNameNew').val()== 0?0: Math.ceil($('#numFreeProNameNew').val()/2)
									}
									//3.预估计重=单票起重,实际品名数=免费品名数
									if ($('#weightCalPredict').val()>=$('#singlePassCrane').val()){
										numFreeProName = $('#numFreeProNameNew').val()
										numProName = numFreeProName
									}
									//超出品名=实际品名-实际免费品名数
									var num = numProName-numFreeProName;
									//清关费=清关费*清关占比
									if ($('#numMaxProName').val() != 0){
										tradeNamePro = toFixed(((gradeNum.size/$('#numMaxProName').val())*100),2)
										wlpmtdList.map((j,k)=>{
											if (tradeNamePro >= j.startSection && tradeNamePro<= j.endSection){
												priceClearanceOpePrice = j.kg
											}
										})
									}
									//占比
									$('#tradeNamePro').val(priceClearanceOpePrice)
									//预估清光费(物流方式清光费*品名占比)
									$('#priceClearanceOpe').val(toFixed(($('#priceClearanceOpeCs').val() * priceClearanceOpePrice/100),2));
									//品名免费数
									$('#numFreeProName').val(numFreeProName)
									$('#numProName').val(numProName);
								} else {
									//超出品名=实际品名-免费品名数
									var num = gradeNum.size-$('#numFreeProNameNew').val();
									//占比
									$('#tradeNamePro').val(100)
									//预估清光费
									$('#priceClearanceOpePrice').val($('#priceClearanceOpe').val())
								}
								$('#numProNameBeyond').val(num>0?num:0);
								//预估品名附加费 = 超出的品名*品名标准
								$('#priceProNameExtraPredict').val($('#nameSurchargePrice').val() * $('#numProNameBeyond').val());
								//预估物流费用 = 预估计重运费*预估材质附加费*预估品名附加费
								$('#priceTranPredict').val(parseFloat($('#priceTranCalWeightPredict').val())+parseFloat($('#priceQualityExtraPredict').val())+parseFloat($('#priceProNameExtraPredict').val())+parseFloat($('#priceClearanceOpe').val()));;
							})

							if (gradeNum.size > $('#numMaxProName').val()){
								layer.msg('已超出物流的上限品名数,请核实后在操作!');
								return
							}

							layer.closeAll();
                            var mjdata=sessionStorage.getItem('dhtable')
                            if(mjdata){
                                mjdata=JSON.parse(mjdata)
                                let newall=[]
                                let endData = [];
                                var isdata=false
                                for (let i = 0; i < res.length; i++) {
                                    var isdata=false
                                    if (newall.indexOf(res[i].guidKc) === -1) {
                                        for (let n = 0; n < mjdata.length; n++) {
                                            if (newall.indexOf(res[i].guidKc) === -1) {
                                                if(res[i].guidKc==mjdata[n].guidKc){
                                                   isdata=true
                                                   endData.push(mjdata[n]);
                                                   newall.push(mjdata[n].guidKc);
                                                }
                                            }
                                        }
                                        if(!isdata){
                                            endData.push(res[i]);
                                            newall.push(res[i].guidKc);
                                        }
                                    }
                                }
								table.reload('dhtable', {data:endData});
                            }else{
                                table.reload('dhtable', {data:res});
                            }
				        }else{
                            layer.msg("请选择数据");
                        }
                	}
                });

                   break;

                case 'mjbtn_save':
                    var objdata=table.checkStatus('dhtable')
                    objdata=objdata.data
                    listData1= table.cache.dhtable;
                    if(objdata.length>0){
                        objdata.forEach(item => {
                        	//根据code删除
                            listData1 = listData1.filter(items => items.guidKc!= item.guidKc);
                        });
						updateNew(listData1,gradeNum,textureList,logisticsMmodeGrads,logisticsMmodeInfoItems,0);
					}else{
                        layer.msg("请选择数据");
                    }
                    break;
            };
        });
    });


	//删除和物流名称修改调用一系列操作
	function  updateNew(listData1,gradeNum,textureList,logisticsMmodeGrads,logisticsMmodeInfoItems,type) {
		weightRealPredict = 0;
		weightVolPredict = 0;
		gradeNum.clear();
		texture = 0;
		surchargeMaterialMax= '';
		listData1.map((n,m)=>{
			//单条数据计算预估重量和抛重
			n.weightPredict = toFixed((n.numPlanDeliver * n.weightPackage),2);
			n.weightVolPredict = toFixed((n.lengthPackage * n.widthPackage * n.heightPackage)* n.numPlanDeliver/$('#coefficientWeight').val(),2);
			// 总预估实重 = 所有的详情 (组装重量（kg）*计划发货数量 )相加
			weightRealPredict=weightRealPredict+Number(n.weightPredict);
			// 总预估抛重 = 所有的详情 (组装长*宽*高/抛货系数*数量/抛货系数)相加
			weightVolPredict=weightVolPredict+Number(n.weightVolPredict);
			if (type == 1){
				//剩余库存=库存数量-计划发货数量
				n.surplusStock= n.numStock - n.numPlanDeliver;
			}
			//不一样的品名数=(商品中文、海关编码、材质中文只要一个不同)
			var join = n.nameGoodsCn + '-' + n.codeGoodsHs + '-' +n.nameMaterialCn;
			gradeNum.add(join);

			//判断是否是混合材质
			if (n.nameMaterialCn != null && typeof n.nameMaterialCn != "undefined") {
				if (n.nameMaterialCn.indexOf(",") == -1) {
					//赋值材质附加费(取最大值)
					for (let j = 0; j < textureList.length; j++) {
						if (textureList[j].materialName == n.nameMaterialCn) {
							if (textureList[j].materialCost > texture) {
								texture = textureList[j].materialCost;
								surchargeMaterialMax = textureList[j].materialName;
							}
						}
					}
				} else {
					var nameMaterialCnList = n.nameMaterialCn.split(",");
					nameMaterialCnList.forEach(item => {
						for (let j = 0; j < textureList.length; j++) {
							if (textureList[j].materialName == item) {
								if (textureList[j].materialCost > texture) {
									texture = textureList[j].materialCost
									surchargeMaterialMax = textureList[j].materialName;
								}
							}
						}
					});
				}
			}
		})



		let weightPrice;
		let phweightPrice;
		let priceClearanceOpePrice=100;
		let predVal;
		let tdjzPrice;
		let pzjzPrice;
		let phjzPrice;
		let tradeNamePro;
		let weightVolPredictNew;
		//判断是否是拼票
		if ($('#stateShareTicketName').val() == '是'){
			//预估计重=实重进行约分
			$('#weightRealPredict').val(toFixed(weightRealPredict,2));
			$('#weightVolPredict').val(toFixed(weightVolPredict,2));
			var weightCalPredict22 = precision(Math.max(weightRealPredict,$('#weightCalBySingle').val()));
			$('#weightCalPredict').val(weightCalPredict22);
			//1.预估计重<单票起重的二分之一,实际品名数=免费品名数/2&向下取整
			let numWeightCal = weightCalPredict22<$('#singlePassCrane').val()/2;
			//实际品名数
			let numProName = gradeNum.size;
			//实际品名免费数
			let numFreeProName;
			if (numWeightCal){
				numFreeProName = $('#numFreeProNameNew').val()== 0?0: Math.floor($('#numFreeProNameNew').val()/2)
			}
			//2.预估计重>=单票起重的二分之一,实际品名数=免费品名数/2&向上取整
			if (!numWeightCal && weightCalPredict22<$('#singlePassCrane').val()){
				numFreeProName = $('#numFreeProNameNew').val()== 0?0: Math.ceil($('#numFreeProNameNew').val()/2)
			}
			if (Number(weightCalPredict22)>= Number($('#singlePassCrane').val())){
				//3.预估计重>=单票起重,实际品名数=免费品名数
				numFreeProName = $('#numFreeProNameNew').val()
			}

			//梯度计重单价=(预估计重满足区间的值)
			tdjzPrice = logisticsMmodeGrads.filter(items => weightCalPredict22 >= items.startSection && weightCalPredict22 <= items.endSection);
			//抛货系数=预估抛重-预估计重
			predVal = toFixed((weightVolPredict - weightCalPredict22),2);
			pzjzPrice = logisticsMmodeInfoItems.filter(items => predVal >= items.startSection && predVal <= items.endSection);
			//计重单价=梯度计重单价+抛重计重单价
			weightPrice = (tdjzPrice[0]?tdjzPrice[0].kg:0) + (pzjzPrice[0]?pzjzPrice[0].kg:0);

			//MAX（预估抛重，单箱起重）（先进行约分）
			weightVolPredictNew = precision(Math.max(weightVolPredict,$('#weightCalBySingle').val()));
			phweightPrice = (tdjzPrice[0]?tdjzPrice[0].kg:0);
			//抛货计重费=预估抛重*梯度计重单价
			$('#jettisonWeightCharge').val(toFixed((weightVolPredictNew * phweightPrice),2))


			//抛重>实重，预估计重费=MIN(预估计重*计重单价,抛货计重费)；抛重<=实重，预估计重费=预估计重*计重单价；计重单价=梯度计重单价+抛重计重单价
			let priceTranCalWeightPredict = toFixed((weightCalPredict22 * weightPrice),2);
			if (weightVolPredict > weightRealPredict){
				if (parseFloat(priceTranCalWeightPredict)>=parseFloat($('#jettisonWeightCharge').val())){
					$('#priceTranCalWeightPredict').val($('#jettisonWeightCharge').val())
				}else {
					$('#priceTranCalWeightPredict').val(priceTranCalWeightPredict)
				}
			} else {
				$('#priceTranCalWeightPredict').val(priceTranCalWeightPredict)
			}

            //清关费=清关费*清关占比
			if ($('#numMaxProName').val() != 0){
				tradeNamePro = toFixed(((gradeNum.size/$('#numMaxProName').val())*100),2)
				wlpmtdList.map((j,k)=>{
					if (tradeNamePro >= j.startSection && tradeNamePro<= j.endSection){
						priceClearanceOpePrice = j.kg
					}
				})
			}
			//占比
			$('#tradeNamePro').val(priceClearanceOpePrice)
			//预估清光费(物流方式清光费*品名占比)
			$('#priceClearanceOpe').val(toFixed(($('#priceClearanceOpeCs').val() * priceClearanceOpePrice/100),2));
			//超出品名=实际品名-实际免费品名数
			var num = numProName-numFreeProName;
			//品名免费数
			$('#numFreeProName').val(numFreeProName)
			$('#numProName').val(numProName);
		} else {
			var weightCalPredict = weightRealPredict>weightVolPredict?weightRealPredict:weightVolPredict;
			$('#weightRealPredict').val(weightRealPredict);
			$('#weightVolPredict').val(toFixed(weightVolPredict,2));
			//预估计重（A1）=MAX（预估实重，预估抛重，单箱起重）然后进行计重约分
			var weightCalPredict22 = precision(Math.max(weightRealPredict,$('#weightCalBySingle').val(),weightVolPredict));
			//用于保存的时候判断
			a1 = weightCalPredict22;
			//预估计重=MAX（A1，单票起重）
			weightCalPredict22 = Math.max(weightCalPredict22,$('#singlePassCrane').val());
			$('#weightCalPredict').val(weightCalPredict22);
			//梯度计重单价=(预估计重满足区间的值)
			tdjzPrice = logisticsMmodeGrads.filter(items => weightCalPredict22 >= items.startSection && weightCalPredict22 <= items.endSection);
			//抛重计重单价=(预估计重-计重的值)
			predVal = toFixed((weightVolPredict - weightCalPredict22),2);
			pzjzPrice = logisticsMmodeInfoItems.filter(items => predVal >= items.startSection && predVal <= items.endSection);
			//计重单价=梯度计重单价
			weightPrice = tdjzPrice[0]?tdjzPrice[0].kg:0;
            //MAX（预估抛重，单箱起重）（先进行约分）
			weightVolPredictNew = precision(Math.max(weightVolPredict,$('#weightCalBySingle').val()));
            phweightPrice = weightPrice;
            //抛货计重费=预估抛重*梯度计重单价
            $('#jettisonWeightCharge').val(toFixed((weightVolPredictNew* phweightPrice),2))

            //预估计重费=(预估计重*计重单价)
            $('#priceTranCalWeightPredict').val(toFixed((weightCalPredict22 * weightPrice),2));


            //超出品名=实际品名-免费品名数
			var num = gradeNum.size-$('#numFreeProNameNew').val();
			//占比
			$('#tradeNamePro').val(100)
			//预估清光费
			$('#priceClearanceOpePrice').val($('#priceClearanceOpe').val())
			$('#numProName').val(gradeNum.size);
		}

		//计重单价
		$('#jzPrice').val(weightPrice)
		//抛货系数
		$('#jettisonCoe').val(predVal)
		//梯度计重单价
		$('#tdjzPrice').val(tdjzPrice[0]?tdjzPrice[0].kg:0)
		//抛重计重单价
		$('#pzjzPrice').val(pzjzPrice[0]?pzjzPrice[0].kg:0)

		//设置表头附加费材质
		$('#priceQualityExtra').val(texture);
		//最大附加费材质
		$('#surchargeMaterialMax').val(surchargeMaterialMax);
		//设置预估材质附加费=材质计费*预估计重
		$('#priceQualityExtraPredict').val(toFixed(($('#priceQualityExtra').val()*$('#weightCalPredict').val()),2));

		//品名
		$('#numProNameBeyond').val(num>0?num:0);
		//预估品名附加费 = 超出的品名*品名标准
		$('#priceProNameExtraPredict').val(toFixed(($('#nameSurchargePrice').val() * $('#numProNameBeyond').val()),2));
		//预估物流费用 = 预估计重运费+预估材质附加费+预估品名附加费+清关费
		$('#priceTranPredict').val(parseFloat($('#priceTranCalWeightPredict').val())+parseFloat($('#priceQualityExtraPredict').val())+parseFloat($('#priceProNameExtraPredict').val())+parseFloat($('#priceClearanceOpe').val()));
		table.reload('dhtable', {data:listData1});
	}

    /**
     * 回调弹框事件
     */
    function getMoreAfter(fieldsList,fields,tindex,fieldName,fieldSearchType,isSearch,isLayer,res) {//弹出框赋值回调
		if(fields=='nameCompany'){
			//修改公司名称,需要重新在设置网店名称
			$('#shopName').val(null);
			$('#nameLogsticsWay').val(null);
			listData1 = [];
			table.reload('dhtable', {data:listData1});
			updateNew(listData1,gradeNum,textureList,logisticsMmodeGrads,logisticsMmodeInfoItems,0);
		}
		if(fields=='shopName'){
			$('#nameLogsticsWay').val(null);
		}
		if(fields=='nameLogsticsPattern'){
			updateNew(listData1,gradeNum,textureList,logisticsMmodeGrads,logisticsMmodeInfoItems,0);
		}
		if(fields=='nameLogsticsWay'){
			//根据物流方式guid获取详情信息
			$.get('/logstics/logisticsmmode/details',{guid:res.guid},function(ress){
				if(ress != null){
					textureList = ress.logisticsMmodeDetailsList;
					logisticsMmodeGrads = ress.logisticsMmodeGrads;
					logisticsMmodeInfoItems = ress.logisticsMmodeInfoItems;
				}else{
					textureList = [];
				}
				updateNew(listData1,gradeNum,textureList,logisticsMmodeGrads,logisticsMmodeInfoItems,0);
			})
		}
	}

	//根据数字未满5满5,未满10满10
	function precision(f) {
		var s = f.toString();
		var rs = s.indexOf('.');
		if (rs != -1) {
			//取出第一位
			var first = s.substring(0,rs);
			//根据第一位小数5来判断，大于0.5以上进1,小于0.5的为0.5
			first = first + '.5';
			if (f < first){
				f = first
			} else if(f > first) {
				f =Math.round(f);
			}
		}
		return f
	}

	//post请求
	function  postUrl(data) {
		$.modal.loading("正在处理中，请稍后...");
		$.post("/business/fbaplanorder/editpost",{infoMap:JSON.stringify(data.field),infoItems:JSON.stringify(listData1),sonData:JSON.stringify(listData2)},function(res){
			$.modal.closeLoading()
			layer.msg(res.msg);
			if(res.code == 0){
				window.location.href = '/business/fbaplanorder/edit?nid=' + res.data + '&isDeliver='+$('#isDeliver').val();
			}
		});
	}


	function isSinglePassCrane(data) {
		if ($('#stateShareTicketName').val() == '否'){
			//A1 < 单票起重，保存提示“头程未满足该渠道的单票发货起重，是否按照该渠道的发货起重去结算发货？”
			if (Number(a1) < Number($('#singlePassCrane').val())){
				$.modal.confirmCom('头程未满足该渠道的单票发货起重，是否按照该渠道的发货起重去结算发货？', function (result) {
					if (result == true){
						postUrl(data)
					}
				})
			} else {
				postUrl(data)
			}
		} else {
			postUrl(data)
		}
	}

	//全选按钮的点击事件
	function checkAll(){
		//获取id的dom元素
		let Id = document.getElementById('all');
		//获取类名为chBox的dom元素
		let chBox = document.getElementsByClassName('chBox');
		let len = chBox.length;
		for(let i=0;i<len;i++){
			//当全选按钮为true时，全部按钮都为true，否则相反
			if(Id.checked){
				chBox[i].checked=true;
			}
			else {
				chBox[i].checked=false;
			}
		}
	};

	//单个按钮的点击事件
	function checkOne(){
		let count=0;
		let chBox = document.getElementsByClassName('chBox');
		let len = chBox.length;
		for(let i=0;i<len;i++){
			//记录单选按钮为true的数量
			if(chBox[i].checked){
				count++;
			}
		}
		//当单选按钮都为true时，全选按钮也为true，否则为false
		if(count==len){
			document.getElementById('all').checked = true;
		}else {
			document.getElementById('all').checked = false;
		}
	}




</script>

</body>
</html>